﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gin.Transactions;
using System.IO;
using System.Xml.Serialization;

namespace Gin.Commands
{
    public class CreateFile: TransactionalCommand, IContentCommand
    {
        [GinArgumentBrowseFile(AllowMultiple = false, Extensions = "*.*", StartFolder = @"C:\")]
        public string SourcePath { get; set; }
        
        [GinArgumentText(Multiline = false, MaxLength = 500)]
        public string DestPath { get; set; }

        public override void Do(ExecutionContext context)
        {
            string absoluteSourcePath = context.ExecutedPackage.GetContentFile(SourcePath);
            DestPath = context.GetAbsolutePathFrom(DestPath);
            File.Copy(absoluteSourcePath, DestPath, true);
        }

        public override TransactionStep Do(ExecutionContext context, Transaction transaction)
        {
            DestPath = context.GetAbsolutePathFrom(DestPath);
            SingleFileStep step = null;
            if (transaction != null)
            {
                step = transaction.CreateStep<SingleFileStep>(this);
            }
            if (File.Exists(DestPath))
            {
                string rollbackFileName = Guid.NewGuid().ToString("N") + ".rlb";
                string dataPath = step.GetPath(context);
                string rollbackFilePath = Path.Combine(dataPath, rollbackFileName);
                step.OldFilePath = rollbackFilePath;
                File.Copy(DestPath, rollbackFilePath);
            }
            Do(context);
            return step;
        }

        public override void Rollback(TransactionStep step)
        {
            SingleFileStep currentStep = (SingleFileStep)step;
            if (File.Exists(currentStep.OldFilePath))
            {
                File.Copy(currentStep.OldFilePath, DestPath, true);
            }
            else
            {
                File.Delete(DestPath);
            }
        }

        [XmlIgnore]
        public string ContentPath
        {
            get
            {
                return SourcePath;
            }
            set
            {
                SourcePath = value;
            }
        }

    }
}
